package com.banciyuan.bcywebview.biz.setting;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.SettingApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.web.WebActivity;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.NetUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by hy on 2015/10/23.
 */
public class FeedBackActivity extends BaseActivity implements View.OnClickListener {

    private boolean feedbacking = false;
    private EditText etFeedBack;
    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private View moreWord;
    private TextView tvNum;
    private RequestQueue mQueue;
    private String versionName;
    private String systemVersion;
    private String modelName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.feedback_layout);
        initArgs();
        initUi();
        initActionbar();
        initAction();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
        versionName = getVersion();
        systemVersion = getSystemVersion();
        modelName = getModelName();
    }

    private String getVersion() {
        PackageManager pm = getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    private String getSystemVersion() {
        return "Android" + Build.VERSION.RELEASE;
    }

    private String getModelName() {
        return new Build().MODEL;
    }


    @Override
    protected void initUi() {
        etFeedBack = (EditText) findViewById(R.id.et_feedback);
        moreWord = findViewById(R.id.ll_moreword);
        tvNum = (TextView) findViewById(R.id.tv_num);
        findViewById(R.id.post_one).setOnClickListener(this);
        findViewById(R.id.post_two).setOnClickListener(this);
        findViewById(R.id.post_three).setOnClickListener(this);
        findViewById(R.id.post_four).setOnClickListener(this);
    }

    @Override
    protected void initAction() {
        etFeedBack.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int length = s.toString().length();
                if (length >= 490) {
                    int remainLength = 500 - length;
                    tvNum.setText(remainLength + "");
                    moreWord.setVisibility(View.VISIBLE);
                } else {
                    moreWord.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.feed_back));
        mActionbarHelper.addItemOneText(getString(R.string.commit));
        mActionbarHelper.setActionCallbacks(new ActionbarHelper.OnActionCallbacks() {
            @Override
            public void onBackClick() {
                finish();
            }

            @Override
            public void onActionClick(int id) {
                if (id == R.id.base_action_bar_home_text_item) {
                    doFeedback(etFeedBack.getText().toString().trim());
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.post_one:
                gotoUtil.gotoAct(this, WebActivity.class, "https://bcy.net/static/post");
                break;
            case R.id.post_two:
                gotoUtil.gotoAct(this, WebActivity.class, "https://bcy.net/static/postgroup");
                break;
            case R.id.post_three:
                gotoUtil.gotoAct(this, WebActivity.class, "https://bcy.net/static/report");
                break;
            case R.id.post_four:
                gotoUtil.gotoAct(this, WebActivity.class, "https://bcy.net/static/share");
                break;
        }
    }

    private void doFeedback(String content) {
        if (feedbacking)
            return;
        if (!NetUtils.checkNetwork(this)) {
            MyToast.show(this, getString(R.string.net_check_first));
            return;
        }
        feedbacking = true;
        String url = HttpUtils.BASE_URL + SettingApi.getFeedback();
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair("opinion", content));
        paramsList.add(new BcyPair("version", versionName));
        paramsList.add(new BcyPair("system", systemVersion));
        paramsList.add(new BcyPair("device", modelName));
        HashMap<String, String> map = HttpUtils.getData(paramsList);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String result) {
                try {
                    JSONObject response = new JSONObject(result);
                    int status = response.getInt(HttpUtils.UPLOAD_STATUS);
                    String data = response.getString(HttpUtils.UPLOAD_DATA);
                    switch (status) {
                        case 1:
                            MyToast.show(FeedBackActivity.this, data);
                            finish();
                            break;
                        default:
                            MyToast.show(FeedBackActivity.this, data);
                            feedbacking = false;
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    feedbacking = false;
                    MyToast.show(FeedBackActivity.this, getString(R.string.network_error));
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volleyError.printStackTrace();
                feedbacking = false;
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, this, map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        mQueue.add(requestParam);
    }
}
